package com.next

import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString

@EqualsAndHashCode(includes = 'username')
@ToString(includes = 'username', includeNames = true, includePackage = false)
class User implements Serializable
{
    private static final long serialVersionUID = 1

    transient springSecurityService

    String username
    String password
    String fullName
    String cellphone

    boolean enabled = true
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired

    Date createdDate = new Date()
    Date modifiedDate = new Date()

    User(String username, String password)
    {
        this()
        this.username = username
        this.password = password
    }

    Set<Role> getAuthorities()
    {
        UserRole.findAllByUser(this)*.role
    }

    def beforeInsert()
    {
        encodePassword()
    }

    def beforeUpdate()
    {
        if (isDirty('password'))
        {
            encodePassword()
        }

        modifiedDate = new Date()
    }

    protected void encodePassword()
    {
        password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
    }

    static transients = ['springSecurityService']

    static constraints = {
        fullName blank: false, password: true
        password blank: false, password: true
        username blank: false, unique: true
        cellphone size: 11..11, blank: true, nullable: true

        accountExpired blank: true, nullable: true
        accountLocked blank: true, nullable: true
        passwordExpired blank: true, nullable: true
    }

    static mapping = {
        table 'login_user'
        password column: '`password`'
        autowire true
    }
}
